import os
import os.path as osp
import json

def txt2json(out_path):
    # === path config
    BASEDIR = osp.abspath('.')
    log_filename = './output_path_picture/results.txt'
    path_log_file = osp.join(BASEDIR, log_filename)

    # === read log file
    # with open(path_log_file, 'r') as fp:
        # contents = fp.read()
    with open(path_log_file, 'r') as fp:
        lines = fp.readlines()
    # print(lines)

    # === collecting
    fileDrawer = {}
    for line in lines:
        one_box_info = line.strip().split(' ')
        image_name = one_box_info[0]
        category_id, confidence, *points = one_box_info[1:]

        # format conversion
        image_name_ = image_name.split('/')[-1]
        points_ = [[eval(points[0]), eval(points[1])],
                   [eval(points[2]), eval(points[3])],
                   [eval(points[4]), eval(points[5])],
                   [eval(points[6]), eval(points[7])]]

        labels = {
            "category_id": category_id,
            # "category_id": 'C',
            "points": points_,
            "confidence": eval(confidence)
        }

        if image_name_ not in fileDrawer:
            fileDrawer[image_name_] = []  # create a list
            fileDrawer[image_name_].append(labels)  # append object info in it
        else:
            fileDrawer[image_name_].append(labels)  # append object info in it
    # print(fileDrawer)
    # print(fileDrawer.keys())
    # print(fileDrawer['9000.tif'])

    fileBibliography = []
    for k in fileDrawer.keys():
        dictItem = {
            "image_name": k,
            "labels": fileDrawer[k]
        }
        fileBibliography.append(dictItem)
    with open(out_path + '/aircraft_results.json', 'w') as f:
        json.dump(fileBibliography, f, indent=2)

# print(fileBibliography)
# print(len(fileBibliography))
# print(fileBibliography[1])

